package test4_12;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.DecimalFormat;


public class ThreadCopy implements Runnable {
    private File fileSrc;  //源地址
    private File fileDes;  //目的地地址
    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadCopy.class);

    public ThreadCopy(File fileSrc, File fileDes) {
        this.fileSrc = fileSrc;
        this.fileDes = fileDes;
    }

    @Override
    public void run() {
        //定义格式：
        DecimalFormat df = new DecimalFormat("##%");

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //创建文件字节输入流，读取本地文件：
            bis = new BufferedInputStream(
                    new FileInputStream(fileSrc));

            //将文件复制到E盘下的E:\Test\----.txt
            bos = new BufferedOutputStream(
                    new FileOutputStream(fileDes));

            //一读一写：
            int len;
            byte[] bytes = new byte[1024];

            //获取文件长度（long字节）
            long total_len = fileSrc.length();
            System.out.println("total_len=" + total_len);

            long length = 0;
            while ((len = bis.read(bytes)) != -1) {
//                System.out.println(file.getName() + df.format(len / total_len));
                Thread.sleep(100);
                bos.write(bytes, 0, len);
                length += len;
                System.out.println(fileSrc.getName() + "文件复制了：" + df.format((double)length / total_len));
            }
            System.out.println(fileSrc.getName() + "文件复制了完毕了！");


        } catch (IOException e) {
            LOGGER.info("文件找不到异常" + e);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                LOGGER.info("关流异常" + e);
            }
            try {
                bos.close();
            } catch (IOException e) {
                LOGGER.info("关流异常" + e);
                ;
            }
        }

    }
}
